# main.py
# StickmanRL 项目主程序（增强版）
# 包含计分、重置、旗帜收集、物理系统

import pygame

# 导入自定义模块
from entities.Stickman import Stickman
from entities.Platform import Platform
from entities.Flag import Flag
from input.handle_keyboard import handle_keyboard
from physics.handle_jump import handle_jump
from physics.apply_gravity import apply_gravity
from physics.update_position import update_position
from physics.check_collision import check_collision
from graphics.draw_stickman import draw_stickman
from graphics.draw_platforms import draw_platforms
from graphics.draw_flag import draw_flag
from graphics.draw_score import draw_score
from config import (
    SCREEN_WIDTH,
    SCREEN_HEIGHT,
    FPS,
    PLATFORMS,
    FLAG_POS,
    GROUND_Y,
    WHITE, FLAG_POSITIONS,
)


def main():
    # === 1. 初始化 Pygame ===
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption("Stickman Jump - collect flags！")
    clock = pygame.time.Clock()
    font = pygame.font.Font(None, 36)  # 用于显示提示文字

    # === 2. 游戏状态初始化函数 ===
    def reset_game():
        """重置游戏状态"""
        stickman = Stickman()
        # 创建所有旗帜
        flags = [Flag(x, y) for x, y in FLAG_POSITIONS]
        score = 0
        game_over = False
        victory = False  # 是否全部收集完成
        return stickman, flags, score, game_over, victory

    # 初始化游戏对象
    stickman, flags, score, game_over, victory = reset_game()

    # 创建平台（不变）
    platforms = [Platform(x, y) for x, y in PLATFORMS]

    # === 3. 主游戏循环 ===
    running = True
    while running:
        # === 4. 处理事件 ===
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    # 按 R 重置游戏
                    stickman, flags, score, game_over, victory = reset_game()
                    print("游戏已重置。")

        # 如果游戏结束，跳过物理更新，只等待重置
        if game_over:
            # 绘制当前画面
            screen.fill(WHITE)
            draw_platforms(screen, platforms)
            draw_stickman(screen, stickman)
            # 绘制所有旗帜
            for flag in flags:
                draw_flag(screen, flag)
            draw_score(screen, score)

            # 显示失败提示
            tip_text = font.render("fall down,press R to begin", True, (255, 0, 0))
            screen.blit(tip_text, (SCREEN_WIDTH // 2 - tip_text.get_width() // 2, SCREEN_HEIGHT // 2))

            pygame.display.flip()
            clock.tick(FPS)
            continue  # 跳过更新

        # === 5. 获取用户输入 ===
        action = handle_keyboard()  # 'left', 'right', 'jump', 'none'
        should_jump = (action == 'jump')

        # === 6. 物理与逻辑更新 ===
        # 水平移动
        if action == 'left':
            stickman.vx = -stickman.speed
        elif action == 'right':
            stickman.vx = stickman.speed
        else:
            stickman.vx = 0

        # 跳跃
        handle_jump(stickman, should_jump)

        # 重力 + 位置 + 碰撞
        apply_gravity(stickman)
        update_position(stickman)
        check_collision(stickman, platforms)

        # === 7. 检查是否收集任何旗帜 ===
        if not game_over and not victory:
            collected_any = False
            for flag in flags:
                if not flag.collected and flag.is_collected_by(stickman):
                    flag.collected = True
                    score += 1
                    collected_any = True
                    print(f"🎉 收集旗帜！当前分数：{score}")

            # 可选：全部收集后胜利
            if all(flag.collected for flag in flags):
                victory = True
                print("🏆 全部旗帜已收集！胜利！")

        # === 8. 检查是否掉落 ===
        if stickman.is_out_of_bounds(GROUND_Y):
            game_over = True
            print("💀 火柴人掉出屏幕！游戏结束。")

        # === 9. 绘制画面 ===
        screen.fill(WHITE)
        draw_platforms(screen, platforms)
        draw_stickman(screen, stickman)
        # 绘制所有旗帜
        for flag in flags:
            draw_flag(screen, flag)
        draw_score(screen, score)

        # 如果游戏结束或胜利，叠加提示
        if game_over or victory:
            if victory:
                tip_text = font.render("Win!press R to restart", True, (0, 255, 0))
            else:
                tip_text = font.render("fall down!press R to restart", True, (255, 0, 0))
            screen.blit(tip_text, (SCREEN_WIDTH // 2 - tip_text.get_width() // 2, SCREEN_HEIGHT // 2))
        pygame.display.flip()
        clock.tick(FPS)

    # === 10. 退出 Pygame ===
    pygame.quit()
    print("游戏已退出。")


# 启动程序
if __name__ == "__main__":
    main()